<template>
	<el-dialog v-model="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="false"
		class="flex-align" style="width: 100%;height: 100%;padding: 30px 24px;margin: 0;background: transparent;">
		<template #header>
			<el-card style="width: 100%;height: 100%;" body-style="padding: 0;" shadow="never">
				<template #header>
					<div class="flex-space-between">
						<div>
							<el-text style="font-size: 16px;">
								销项发票
							</el-text>
						</div>
						<div>
							<el-button @click="closeDialog">取消</el-button>
							<!-- <el-button @click="closeDialog">
								保存并继续创建
								<el-icon style="margin-left: 4px;">
									<ArrowDown />
								</el-icon>
							</el-button> -->
							<el-button type="primary" @click="submitForm(vFormRef)">
								保存
							</el-button>
						</div>
					</div>
				</template>
				<el-scrollbar ref="scrollbarRef" @scroll="handleScroll"
					:style="`height: calc(100vh - 69px - ( 30px + 30px));`">
					<el-form :model="formData" :rules="rules" ref="vFormRef" label-position="top" label-width="50px"
						style="padding: 16px;">
						<el-form-item label="开票状态" prop="invoiceStatus" class="form-item-bg">
							<el-select @clear="selectClear('invoiceStatus')" v-model="formData.invoiceStatus"
								@change="(value:any)=>selectChange(value,'invoiceStatus')" multiple ref="invoiceStatus"
								clearable>
								<el-option v-for="(item, key) in invoiceStatusOption" :key="key" :label="item?.label"
									:value="item?.value" disabled>
									<!--  -->
									<el-tag style="border: 0;" :color="item?.color" round effect="dark">
										{{ item?.label }}
									</el-tag>
									<!--  -->
								</el-option>
								<!--  -->
								<template #tag>
									<el-tag style="border: 0;" v-show="invoiceStatusOption[invoiceStatusIndex]?.value"
										:color="invoiceStatusOption[invoiceStatusIndex]?.color" round effect="dark">
										{{ invoiceStatusOption[invoiceStatusIndex]?.label }}
									</el-tag>
								</template>
							</el-select>
						</el-form-item>
						<el-form-item label="所属客户" prop="customer">
							<el-select @clear="selectClear('customer')" v-model="formData.customer"
								@change="(value:any)=>selectChange(value,'customer')" multiple ref="customer" clearable>
								<el-option v-for="item in customerOption" :key="key" :label="item?.label"
									:value="item?.value">
									<!--  -->
									<div class="flex-align-center">
										<el-icon :color="item?.color">
											<component :is="item?.icon"></component>
										</el-icon>
										<!--  -->
										<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
									</div>
								</el-option>
								<!--  -->
								<template #tag>
									<div style="padding-left: 6px;">
										<div>
											<div class="flex-align-center">
												<el-icon :color="customerOption[customerIndex]?.color">
													<component :is="customerOption[customerIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{customerOption[customerIndex]?.label}}</el-text>
											</div>
										</div>
									</div>
								</template>
							</el-select>
						</el-form-item>
						<el-form-item label="所属销售订单" prop="salesOrder">
							<el-select @clear="selectClear('salesOrder')" v-model="formData.salesOrder"
								@change="(value:any)=>selectChange(value,'salesOrder')" multiple ref="salesOrder"
								clearable>
								<el-option v-for="item in salesOrderOption" :key="key" :label="item?.label"
									:value="item?.value">
									<!--  -->
									<div class="flex-align-center">
										<el-icon :color="item?.color">
											<component :is="item?.icon"></component>
										</el-icon>
										<!--  -->
										<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
									</div>
								</el-option>
								<!--  -->
								<template #tag>
									<div style="padding-left: 6px;">
										<div>
											<div class="flex-align-center">
												<el-icon :color="salesOrderOption[salesOrderIndex]?.color">
													<component :is="salesOrderOption[salesOrderIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{salesOrderOption[salesOrderIndex]?.label}}</el-text>
											</div>
										</div>
									</div>
								</template>
							</el-select>
						</el-form-item>
						<el-form-item label="发票类型" prop="invoiceType">
							<el-select @clear="selectClear('invoiceType')" v-model="formData.invoiceType"
								@change="(value:any)=>selectChange(value,'invoiceType')" multiple ref="invoiceType"
								clearable>
								<el-option v-for="(item, key) in invoiceTypeOption" :key="key" :label="item?.label"
									:value="item?.value">
									<!--  -->
									<el-tag style="border: 0;" :color="item?.color" round effect="dark">
										{{ item?.label }}
									</el-tag>
									<!--  -->
								</el-option>
								<!--  -->
								<template #tag>
									<el-tag style="border: 0;" v-if="invoiceTypeOption[invoiceTypeIndex]?.value"
										:color="invoiceTypeOption[invoiceTypeIndex]?.color" round effect="dark">
										{{ invoiceTypeOption[invoiceTypeIndex]?.label }}
									</el-tag>
								</template>
							</el-select>
						</el-form-item>
						<el-form-item label="开票金额" prop="billingAmount">
							<el-input placeholder="请填写" type="number" v-model="formData.billingAmount"
								clearable></el-input>
						</el-form-item>
						<el-form-item label="备注" prop="remark">
							<el-input type="text" v-model="formData.remark" clearable></el-input>
						</el-form-item>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="开票申请人" prop="billingApplicant">
									<el-input placeholder="请填写" type="text" readonly v-model="formData.billingApplicant"
										clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="申请日期" prop="applicationDate">
									<el-date-picker placeholder="请选择" v-model="formData.applicationDate"
										style="width:100%;" type="date" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="开票抬头" prop="billingTitle">
									<el-input placeholder="请填写" type="text" v-model="formData.billingTitle"
										clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="开票税号" prop="billingTaxNumber">
									<el-input placeholder="请填写" type="text" v-model="formData.billingTaxNumber"
										clearable></el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="开户行" prop="bankOfDeposit">
									<el-input placeholder="请填写" type="text" v-model="formData.bankOfDeposit"
										clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="银行账号" prop="bankAccount">
									<el-input placeholder="请填写" type="text" v-model="formData.bankAccount"
										clearable></el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-form-item label="收票地址" prop="billingAddress">
							<el-input type="text" clearable v-model="formData.billingAddress">
								<template #prefix>
									<el-button size="small" text :icon="Position" @click="geolocations">
									</el-button>
									<el-icon class="is-loading" v-if="formData.loading">
										<svg class="circular" viewBox="-10, -10, 50, 50">
											<path class="path" d="
										            M 30 15
										            L 28 17
										            M 25.61 25.61
										            A 15 15, 0, 0, 1, 15 30
										            A 15 15, 0, 1, 1, 27.99 7.5
										            L 15 15
										          " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)" />
										</svg>
									</el-icon>
								</template>
							</el-input>
						</el-form-item>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="附件" prop="attachment">
									<el-input type="text" readonly clearable>
										<template #prefix>
											<el-upload v-model:file-list="formData.files" action="/api/oss/policy"
												:on-success="onSuccess" :headers="{'Authorization':cookie.get('token')}"
												:limit="1">
												<el-button v-if="!formData.attachment" text :icon="UploadFilled">
													上传图片
												</el-button>
												<el-image v-else preview-teleported
													style="width: 30px; height: 30px;margin: 10px auto;"
													:src="formData.attachment"
													:preview-src-list="[formData.attachment]" />
											</el-upload>
										</template>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="开票日期" prop="billingDate">
									<el-date-picker placeholder="请选择" v-model="formData.billingDate" style="width:100%;"
										type="date" />
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</el-scrollbar>
				<!--  -->
			</el-card>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import request from '../../../utils/request';
	import {Position,UploadFilled, UserFilled, WalletFilled, CirclePlus, DocumentAdd, Delete } from '@element-plus/icons-vue';
	import { mergeObjects, formatNumber } from '../../../utils';
	import { useSelect } from '../../../utils/mixins';
	import { ElMessage, FormInstance } from 'element-plus';
	import { getShipments } from '../../../api/shipmentAPI';
	import { jwtDecode } from 'jwt-decode';
	import cookie from 'js-cookie';
	const emits = defineEmits(['update']);
	const { handSelectChange } = useSelect();
	const router = useRouter();
	const route = useRoute();
	const vFormRef = ref(null);
	const loading = ref(false);

	// 表单
	const formData = ref({
		invoiceStatusId: null,//开票状态
		invoiceStatus: [],
		customerId: null,//客户
		customer: [],
		salesOrderId: null,//销售订单
		salesOrder: [],
		invoiceTypeId: null,//发票类型
		invoiceType: [],
		billingAmount: null,//开票金额
		remark: null,//备注
		billingApplicant: null,//开票申请人
		applicationDate: null,//申请日期
		billingTitle: null,//开票抬头
		billingTaxNumber: null,//开票税号
		bankOfDeposit: null,//开户行
		bankAccount: null,//银行账号
		billingAddress: null,//收票地址
		attachment: null,//附件
		files:[],
		billingDate: null,//开票日期
		loading:false,
	});
	//验证
	const rules = reactive({
		invoiceStatus: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//开票状态
		customer: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//客户
		salesOrder: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//销售订单
		invoiceType: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//发票类型
		billingAmount: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//开票金额
		remark: [],//备注
		billingApplicant: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//开票申请人
		applicationDate: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//申请日期
		billingTitle: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//开票抬头
		billingTaxNumber: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//开票税号
		bankOfDeposit: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//开户行
		bankAccount: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//银行账号
		billingAddress: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//收票地址
		attachment: [],//附件
		billingDate: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//开票日期
	});
	const pageData = ref({
		pageNum: 1,
		pageSize: 1000,
		total: 0,
		pages: 0,
	});
	//开票状态
	const invoiceStatusOption = ref([]);
	const invoiceStatusIndex = ref(-1);
	const invoiceStatus = ref(null);
	//客户
	const customerOption = ref([]);
	const customerIndex = ref(-1);
	const customer = ref(null);
	//销售订单
	const salesOrderOption = ref([]);
	const salesOrderIndex = ref(-1);
	const salesOrder = ref(null);
	//发票类型
	const invoiceTypeOption = ref([]);
	const invoiceTypeIndex = ref(-1);
	const invoiceType = ref(null);
	//
	const dialogVisible = ref(false);
	/**
	 * 打开弹出层
	 */
	const openDialog = () => {
		dialogVisible.value = true;
		setTimeout(async () => {
			const result = await getPageId();
			//
			if (result) {
				getSelectKData();
				getInvoiceStatusList();
				getInvoiceTypeList();
				if (!route.query.id) {
					formData.value.invoiceStatusId = 186;
					formData.value.invoiceStatus = [186];
					invoiceStatusIndex.value = 0;
				}
			}
		}, 10);
	}
	/**
	 * 关闭弹出层
	 */
	const closeDialog = () => {
		dialogVisible.value = false;
		vFormRef.value.resetFields();
		//清空url参数
		router.push({ query: {} });
	}
	//获取当前页面的数据
	const getPageId = async () => {
		if (!route.query.id) {
			const token = cookie.get('token');
			const decodedToken : {
				username : string
			} = jwtDecode(token);
			// console.log('decodedToken--->', decodedToken);
			//
			formData.value.billingApplicant = decodedToken?.username;
			//
			return true;
		}
		//
		const result = await request({
			url: '/SalesReceipt/SalesInvoiceById',
			params: {
				id: route.query.id
			},
		});
		//
		console.log('getPageId --->', result);
		//
		formData.value = { ...result.data.t };
		//
		return true;
	}
	//改变
	const selectChange = (value : Array<any>, type : string, key : number) => {
		//所有下拉框的配置列表
		const typeList = [{
			type: 'invoiceStatus', //哪一个下拉框，根据ref
			option: invoiceStatusOption, //下拉列表选项
			indexVar: invoiceStatusIndex, //当前选中项
			idVar: 'invoiceStatusId', //当前id值
			blurRef: invoiceStatus, //ref
		}, {
			type: 'customer', //哪一个下拉框，根据ref
			option: customerOption, //下拉列表选项
			indexVar: customerIndex, //当前选中项
			idVar: 'customerId', //当前id值
			blurRef: customer, //ref
			fun: getSelectSOrderById
		}, {
			type: 'invoiceType', //哪一个下拉框，根据ref
			option: invoiceTypeOption, //下拉列表选项
			indexVar: invoiceTypeIndex, //当前选中项
			idVar: 'invoiceTypeId', //当前id值
			blurRef: invoiceType, //ref
		}, {
			type: 'salesOrder', //哪一个下拉框，根据ref
			option: salesOrderOption, //下拉列表选项
			indexVar: salesOrderIndex, //当前选中项
			idVar: 'salesOrderId', //当前id值
			blurRef: salesOrder, //ref
		},];
		//
		handSelectChange(formData, typeList, value, type, key);
	}
	//获取客户
	const getSelectKData = async () => {
		const result = await request({
			url: '/SalesReceipt/selectKData',
		});
		console.log('getSelectKData --->', result);
		customerOption.value = [];
		result.data.t.customers.forEach((item : any, key : number) => {
			customerOption.value.push({
				label: `${item.customerName}`,
				value: item.customerId,
				icon: UserFilled,
				color: '#82b51b'
			});
			if (formData.value.customerId === item.customerId) {
				formData.value.customer = [item.customerId];
				customerIndex.value = key;
				getSelectSOrderById(item.customerId);
			}
		});
	}
	//获取开票状态
	const getInvoiceStatusList = async () => {
		const data = await getShipments('invoice_status');
		invoiceStatusOption.value = [];
		data.forEach((item : any, key : number) => {
			invoiceStatusOption.value.push(item);
			//
			if (formData.value.invoiceStatusId === item.value) {
				formData.value.invoiceStatus = [item.value];
				invoiceStatusIndex.value = key;
			}
		});
	}
	//根据id获取销售订单
	const getSelectSOrderById = async (customerId : number) => {
		const result = await request({
			url: '/SalesReceipt/selectSOrder',
			params: { customerId }
		});
		console.log('getSelectSOrderById --->', result);
		salesOrderOption.value = [];
		result.data.t.forEach((item : any, key : number) => {
			salesOrderOption.value.push({
				label: `${item.orderNumber}_${formatNumber(item.orderTotalAmount, '元')}`,
				value: item.orderId,
				icon: UserFilled,
				color: '#82b51b'
			});
			if (formData.value.salesOrderId === item.orderId) {
				formData.value.salesOrder = [item.orderId];
				salesOrderIndex.value = key;
			}
		});
	}
	//获取发票类型
	const getInvoiceTypeList = async () => {
		const data = await getShipments('invoice_type');
		invoiceTypeOption.value = [];
		data.forEach((item : any, key : number) => {
			invoiceTypeOption.value.push(item);
			//
			if (formData.value.invoiceTypeId === item.value) {
				formData.value.invoiceType = [item.value];
				invoiceTypeIndex.value = key;
			}
		});
	}
	//
	//提交表单
	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				console.log('submitForm ---> ', formData.value);
				const data = { ...formData.value };
				delete data.customer;
				delete data.invoiceStatus;
				delete data.invoiceType;
				delete data.salesOrder;
				let type = '';
				if (!route.query.id) {
					type = '/saveSalesInvoice';
				} else {
					type = '/updateSalesInvoice';
				}
				//
				const result = await request({
					url: '/SalesReceipt' + type,
					data: data,
					method: 'post'
				});
				//
				console.log('submitForm--->', result);
				//

				if (result.data.code === 200) {
					ElMessage.success({
						message: '操作成功！'
					});

				} else {
					ElMessage.error({
						message: result.data.msg
					});
				}
				//
				setTimeout(() => {
					closeDialog();
					emits('update');
				}, 1);
			} else {
				//
				console.log('error submit!', fields);
			}
		});
	}
	//凭证上传成功
	const onSuccess = (res : any) => {
		console.log('onSuccess --->', res);
		//
		formData.value.attachment = res.t;
	}
	//获取位置
	const geolocations = async () => {
		formData.value.loading = true;
		const { coords: { latitude, longitude } } = await geolocation();
		//
		const result = await request({
			url: 'http://localhost:3000/api/ip/getIpInfoPlus',
			params: { latitude, longitude }
		});
		console.log('geolocations --->', result);
		const { ad_info, address_reference: { town } } = result.data.result;
		const location = `${ad_info.nation}-${ad_info.province}-${ad_info.city} ${ad_info.district}${town.title}${town._dir_desc}`;
		// if (formData.value.location) {
		console.log('location --->', location);
		formData.value.billingAddress = location;
		formData.value.loading = false;
		// }
	}
	//获取经纬度信息
	const geolocation = () : Promise<any> => {
		return new Promise((resolve, reject) => {
			navigator.geolocation.getCurrentPosition(
				(result) => {
					console.log('result--->', result);
					resolve(result);
				},
				(error) => {
					switch (error.code) {
						// 处理错误
					}
					reject(error);
				},
				{
					timeout: 5000,
				}
			);
		});
	}
	//
	defineExpose({
		openDialog
	});
</script>
<style>
	@import '../../../assets/css/my-form-item.css';

	.form-item-bg {
		background-color: #bfdfff;
	}

	.form-item-bg1 {
		background-color: #a5f2e5;
	}

	.my.el-input .el-input__inner {
		opacity: 0;
	}

	/*  */
	.avatar-uploader {
		width: 178px;
		height: 178px;
	}

	.avatar-uploader .avatar {
		width: 100%;
		height: 100%;
	}

	.avatar-uploader .el-upload {
		width: 100%;
		height: 100%;
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.el-scrollbar__view {
		display: block !important;
	}
	.el-upload-list--text {
		display: none;
	}
	/*  */
</style>

<style scoped lang="scss">
	@import '../../../assets/css/index.scss';
</style>